<script lang="ts" setup>
import "@vue-office/docx/lib/index.css";
import "@vue-office/excel/lib/index.css";
import { defineAsyncComponent, defineProps, onMounted } from "vue";
import type { FileProps } from "@/components/RefilePreview/types";
import { useHooks } from "@/components/RefilePreview/hook";

const VueOfficeDocx = defineAsyncComponent(() => import("@vue-office/docx"));
const VueOfficeExcel = defineAsyncComponent(() => import("@vue-office/excel"));
const VueOfficePdf = defineAsyncComponent(() => import("@vue-office/pdf"));
const RePlayer = defineAsyncComponent(
  () => import("@/components/RePlayer/src/index.vue")
);

defineOptions({
  name: "ReFilePreview"
});

const props = withDefaults(defineProps<FileProps>(), {
  id: null,
  type: "",
  fileType: "",
  raw: () => new File([], ""),
  filePath: ""
});

const {
  excelOptions,
  src,
  filePreviewRef,
  renderedHandler,
  errorHandler,
  renderTheFile,
  isImage,
  isVideo,
  isText,
  isAudio
} = useHooks(props);

onMounted(() => {
  renderTheFile(); // 渲染文件
});

defineExpose({
  filePreviewRef
});
</script>

<template>
  <div ref="filePreviewRef" class="file-preview">
    <vue-office-docx
      v-if="props.fileType === 'docx' || props.fileType === 'doc'"
      :src="src"
      @rendered="renderedHandler"
      @error="errorHandler"
    />
    <vue-office-excel
      v-if="props.fileType === 'xlsx' || props.fileType === 'xls'"
      :src="src"
      width="100%"
      height="100%"
      :auto-resize="true"
      :enable-scrollbars="true"
      :options="excelOptions"
      @rendered="renderedHandler"
      @error="errorHandler"
    />
    <vue-office-pdf
      v-if="props.fileType === 'pdf'"
      :src="src"
      @rendered="renderedHandler"
      @error="errorHandler"
    />
    <el-image
      v-if="isImage(props.fileType)"
      :preview-teleported="true"
      fit="cover"
      class="w-[200px] align-left"
      :src="src"
      title="点击查看大图"
      :preview-src-list="[src]"
    />
    <RePlayer v-if="isVideo(props.fileType)" :url="src" :controls="true" />
    <div v-if="isText(props.fileType)">
      <pre v-html="src" />
    </div>
    <audio v-if="isAudio(props.fileType)" :src="src" controls />
  </div>
</template>

<style lang="scss" scoped>
.file-preview {
  width: 100%;
  height: 500px;
  overflow: auto;
  text-align: left;
}
</style>
